package com.dinero.pagecontents.viewmodel;

import android.content.Context
import android.graphics.Color
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.android.basekt.base.BaseViewEventConstants
import com.android.basekt.viewmodel.BaseViewModel
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import com.bigkoo.pickerview.view.TimePickerView
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.ToastUtils
import com.dinero.pagecontents.R
import com.dinero.pagecontents.bean.*
import com.dinero.pagecontents.net.ApiClient
import com.dinero.pagecontents.util.UserInfoUtils
import com.dinero.pagecontents.bean.BaseBean
import com.dinero.pagecontents.bean.isNetSuccess
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class CertifyPersonInformationViewModel : BaseViewModel() {

    var mInformationDatas = MutableLiveData<MutableList<Continuing>>()
    var mOrdId = MutableLiveData<String>()
    var mProId = MutableLiveData<String>()

    var bankType = MutableLiveData<Matched>()
    var bankCode = MutableLiveData<Matched>()

    var mSelectContent = MutableLiveData<Matched>()
    var mBrithDayContent = MutableLiveData<String>()


    var mFristContactDatas: ArrayList<Matched> = arrayListOf()
    var mFristContactName = MutableLiveData<String>("")
    var mFristContactPhone = MutableLiveData<String>("")
    var mFristContact = MutableLiveData<Matched>()

    var mTwoContactDatas: ArrayList<Matched> = arrayListOf()
    var mTwoContactName = MutableLiveData<String>("")
    var mTwoContactPhone = MutableLiveData<String>("")
    var mTwoContact = MutableLiveData<Matched>()
    var mFinishFilter = MutableLiveData<Boolean>()

    //person work bank
    var mCurViewType = "person"

    var banckCardConfirmEvent = MutableLiveData<String>()


    fun getContactDatas() {
        viewModelScope.launch {
            BaseViewEventConstants.SHOW_LOADING_VIEW.publish()
            try {
                if (!NetworkUtils.isConnected()) {
                    ToastUtils.showShort("No internet")
                    return@launch
                }
                var netBean = netApi {
                    var params = hashMapOf<String, String>()
                    params.put("best", UserInfoUtils.mPhoneNum)
                    params.put("heartily35", mProId.value.toString())
                    ApiClient.instance.getApiService().getCertifyContactInformation(params)
                }
                var dataBean = netBean.await()
                dataBean?.let {
                    if (dataBean.code.isNetSuccess()) {
                        mFristContactPhone.value = dataBean.data.insensible.greatest
                        mFristContactName.value = dataBean.data.insensible.happier

                        mTwoContactName.value = dataBean.data.insensible.future
                        mTwoContactPhone.value = dataBean.data.insensible.judging

                        mFristContactDatas.clear()
                        mFristContactDatas.addAll(dataBean.data.insensible.hand)

                        mTwoContactDatas.clear()
                        mTwoContactDatas.addAll(dataBean.data.insensible.lenient27)

                        var contactData =
                            getContactName(mFristContactDatas, dataBean.data.insensible.sense)

                        contactData?.let {
                            mFristContact.value = it
                        }
                        var contact2Data =
                            getContactName(mTwoContactDatas, dataBean.data.insensible.acting26)

                        contact2Data?.let {
                            mTwoContact.value = it
                        }
                    }
                }

            } catch (e: Exception) {
            }
            BaseViewEventConstants.DISMISS_VIEW.publish()
        }
    }

    fun getContactName(datas: List<Matched>, id: String): Matched? {
        for (matched in datas) {
            if (matched.oxford == id) {
                return matched
            }
        }
        return null
    }

    fun getData(proId: String) {
        viewModelScope.launch {
            try {
                if (!NetworkUtils.isConnected()) {
                    ToastUtils.showShort("No internet")
                    return@launch
                }
                BaseViewEventConstants.SHOW_LOADING_VIEW.publish()

                var netBean = netApi {
                    var params = hashMapOf<String, String>()
                    params.put("best", UserInfoUtils.mPhoneNum)
                    params.put("heartily35", proId)

                    if (mCurViewType == "person") {
                        ApiClient.instance.getApiService().getCertifyPersonInformation(params)
                    } else if (mCurViewType == "work") {
                        ApiClient.instance.getApiService().getCertifyWorkInformation(params)
                    } else if (mCurViewType == "bank") {
                        ApiClient.instance.getApiService().getCertifyBankInformation(params)
                    } else {
                        ApiClient.instance.getApiService().getCertifyPersonInformation(params)
                    }

                }
                var dataBean = netBean.await()
                dataBean?.let {
                    if (dataBean.code.isNetSuccess()) {
                        var bankMatched: Matched? = null
                        var bankCodeMatched: Matched? = null
                        var datas = dataBean.data.continuing
                        datas.forEach {
                            it.edMaxLenth = 9999
                            if (it.intent.contentEquals("B", true) && !it.howqw.isNullOrEmpty()
                            ) {
                                var data = getContactName(it.matched, it.howqw)
                                if (data != null) {
                                    it.selData = Matched()
                                    it.selData.oxford = data.oxford
                                    it.selData.attended = data.attended
                                    it.selData.thanked = data.thanked
                                    if (it.between == "bankType") {
                                        bankMatched = it.selData
                                    } else if (it.between == "bankCode") {
                                        bankCodeMatched = it.selData
                                    }
                                } else {
                                    it.selData = Matched()
                                    if (mCurViewType == "bank" && it.between == "bankType" && it.matched.isNotEmpty()) {
                                        var data = it.matched[0]
                                        it.selData.oxford = data.oxford
                                        it.selData.attended = data.attended
                                        it.selData.thanked = data.thanked
                                        bankMatched = it.selData
                                    }
                                }
                            } else {
                                it.selData = Matched()
                            }
                        }

                        mInformationDatas.value = datas

                        if (bankMatched != null) {
                            bankType.value = bankMatched
                        }

                        if (bankCodeMatched != null) {
                            bankCode.value = bankCodeMatched
                        }

                    } else {
                        ToastUtils.showShort(dataBean.message)
                    }
                }

                BaseViewEventConstants.DISMISS_VIEW.publish()
            } catch (e: Exception) {
                BaseViewEventConstants.DISMISS_VIEW.publish()
                Log.i("Exception", "getData:${e.toString()} ")
            }

            delay(200)

        }
    }

    fun submitContactData() {
        viewModelScope.launch {
            try {
                BaseViewEventConstants.SHOW_LOADING_VIEW.publish()
                var netBean = netApi {
                    var params = hashMapOf<String, String>()
                    params["resolution"] = mFristContactPhone.value.toString()
                    params["points"] = mFristContactName.value.toString()
                    mFristContact.value?.let {
                        params.put("these", it.oxford.toString())
                    }
                    params["heartily35"] = mProId.value.toString()
                    params["amiable"] = mTwoContactPhone.value.toString()
                    params["perfectly"] = mTwoContactName.value.toString()

                    mTwoContact.value?.let {
                        params.put("consideration", it.oxford.toString())
                    }

                    ApiClient.instance.getApiService().submitCertifyContactInformation(params)
                }
                var dataBean = netBean.await()
                dataBean?.let {
                    if (dataBean.code.isNetSuccess()) {
                        BaseViewEventConstants.FINISH_VIEW.publish()
                    } else {
                        ToastUtils.showShort(dataBean.message)
                    }
                }

                BaseViewEventConstants.DISMISS_VIEW.publish()
            } catch (e: Exception) {
                BaseViewEventConstants.DISMISS_VIEW.publish()
            }
        }
    }

    fun showBankCardConfirm() {

        var cardNo = ""
        mInformationDatas.value?.forEach {
            if (it.intent.contentEquals("A", true)
                && it.between == "cardNo"
            ) {
                cardNo = it.howqw
            }
        }

        Log.i("Bank", "showBankCardConfirm:cardNo==>${cardNo} ")
        if (!cardNo.isNullOrEmpty()) {
            banckCardConfirmEvent.value = cardNo
        } else {
            submitDataInfo()
        }
    }

    fun submitDataInfo() {
        viewModelScope.launch {
            try {
                BaseViewEventConstants.SHOW_LOADING_VIEW.publish()

                var params = hashMapOf<String, String>()
                params.put("anxieties", mOrdId.value.toString())
                params.put("heartily35", mProId.value.toString())

                mInformationDatas.value?.forEach {
                    if (it.intent.contentEquals("B", true)) {
                        params.put(it.between, it.selData.oxford.toString())
                    } else if (it.intent.contentEquals("A", true)
                        || it.intent.contentEquals("F", true)
                    ) {
                        params.put(it.between, it.howqw)
                    }
                }
                var netBean = netApi {
                    if (mCurViewType == "person") {
                        ApiClient.instance.getApiService().submitCertifyPersonInformation(params)
                    } else if (mCurViewType == "work") {
                        ApiClient.instance.getApiService().submitCertifyWorkInformation(params)
                    } else if (mCurViewType == "bank") {
                        ApiClient.instance.getApiService().submitCertifyBankInformation(params)
                    } else {
                        ApiClient.instance.getApiService().submitCertifyPersonInformation(params)
                    }
                }

                var dataBean = netBean.await()
                dataBean?.let {
                    if (dataBean.code.isNetSuccess()) {
                        BaseViewEventConstants.FINISH_VIEW.publish()
                    } else {
                        ToastUtils.showShort(dataBean.message)
                    }
                }

                BaseViewEventConstants.DISMISS_VIEW.publish()
            } catch (e: Exception) {
                BaseViewEventConstants.DISMISS_VIEW.publish()
            }
        }
    }

    fun submitData() {
        if (mCurViewType == "person") {
            submitDataInfo()
        } else if (mCurViewType == "work") {
            submitDataInfo()
        } else if (mCurViewType == "bank") {
            showBankCardConfirm()
        } else {
            submitDataInfo()
        }
    }


    var mContext: Context? = null

    val enumOptions: OptionsPickerView<Matched> by lazy {
        OptionsPickerBuilder(mContext,
            OnOptionsSelectListener { options1, options2, options3, v -> //返回的分别是三个级别的选中位置
                curEnumOptions?.let {
                    mSelectContent.value = it.get(options1)
                }
            }).setLayoutRes(R.layout.pickerview_custom_options) {
            val tvSubmit = it.findViewById<View>(R.id.tv_finish) as TextView
            val ivCancel = it.findViewById<View>(R.id.iv_cancel) as TextView
            tvSubmit.setOnClickListener {
                enumOptions.returnData()
                enumOptions.dismiss()
            }
            ivCancel.setOnClickListener { enumOptions.dismiss() }
        }
            .setTitleText("")
            .setContentTextSize(24)
            .setDividerColor(Color.LTGRAY) //设置分割线的颜色
            .setSelectOptions(0, 1) //默认选中项
            .setBgColor(Color.WHITE)
            .isRestoreItem(true) //切换时是否还原，设置默认选中第一项。
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .setLabels("", "", "")
            .setOutSideColor(0x00097B77) //设置外部遮罩颜色#097B77
            .setOptionsSelectChangeListener { options1, options2, options3 ->
//                val str = "options1: $options1\noptions2: $options2\noptions3: $options3"
//                Toast.makeText(this@MainActivity, str, Toast.LENGTH_SHORT).show()
            }
            .build()
    }
    val mBrithDayView: TimePickerView by lazy {
        val selectedDate = Calendar.getInstance() //系统当前时间
        val startDate = Calendar.getInstance()
        startDate[2014, 1] = 23
        val endDate = Calendar.getInstance()
        endDate[2027, 2] = 28
        //时间选择器 ，自定义布局
        TimePickerBuilder(
            mContext
        ) { date, v -> //选中事件回调
            mBrithDayContent.value = getTime(date).toString()

        }
            .setDate(selectedDate)
            .setRangDate(startDate, endDate)
            .setLayoutRes(R.layout.pickerview_birthday_time) { v ->
                val tvSubmit = v.findViewById<View>(R.id.tv_finish) as TextView
                val ivCancel = v.findViewById<View>(R.id.iv_cancel) as TextView
                tvSubmit.setOnClickListener {
                    mBrithDayView.returnData()
                    mBrithDayView.dismiss()
                }
                ivCancel.setOnClickListener { mBrithDayView.dismiss() }
            }
            .setContentTextSize(24)
            .setType(booleanArrayOf(true, true, true, false, false, false))
            .setLabel("", "", "", "", "", "")
            .setLineSpacingMultiplier(1.2f)
            .setTextXOffset(0, 0, 0, 40, 0, -40)
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .setDividerColor(-0xdb5263)
            .build()
    }


    var curEnumOptions: List<Matched>? = null

    fun showEnumView(mutableList: List<Matched>) {
        curEnumOptions = mutableList
        enumOptions.setPicker(mutableList)
        enumOptions.show()
    }

    private fun getTime(date: Date): String? { //可根据需要自行截取数据显示
        val format = SimpleDateFormat("dd-MM-yyyy")
        return format.format(date)
    }


    override fun finishView() {
        mFinishFilter.value = true
    }

}